#include "PlayerPlane.h"
#include "Config.h"
#include "WeaponBank.h"
#include "BaseObject.h"
#include "MainLayer.h"
#include "BulletFactory.h"
#include "BulletsBank.h"
#include "StrategyBank.h"
#include "PlaneShotStrategy.h"
#include "EffectFactory.h"
#include "RocketPlaneStrangtegy.h"


PlayerPlane::PlayerPlane(void)
{
	_listSupportedWeaponKey = NULL;
	_weaponLevel = 1;
	_health = 0;
	_maxHealth = 0;
	_healthBar = NULL;
	_strategy = NULL;
	_rocketStrategy = NULL;
	_isProtected = false;
	_protectBoundBox = CCSizeZero;
}


PlayerPlane::~PlayerPlane(void)
{
	CC_SAFE_RELEASE(_listSupportedWeaponKey);
	CC_SAFE_RELEASE(_healthBar);
	CC_SAFE_RELEASE(_strategy);
	CC_SAFE_RELEASE(_rocketStrategy);
}

bool PlayerPlane::init()
{
	if (!BaseObject::init())
		return false;
	setSupportedWeaponKeys(CCArray::create());

	//CCParticleSystemQuad* particle = CCParticleSystemQuad::create("RocketParticle.plist");
	//particle->setRotation(45);
	//addChild(particle);

	return true;

}


void PlayerPlane::onEnter()
{
	BaseObject::onEnter();
	//setWeaponLevel(9);
	//addChild(RocketPlaneStrangtegy::create());
}

void PlayerPlane::onShooting(float dt)
{
	if (!_strategy)
		return;
	dynamic_cast<PlaneShotStrategy*>(_strategy)->shoot(dt);
}

void PlayerPlane::onExit()
{
	BaseObject::onExit();
}

int PlayerPlane::getWeaponLevel()
{
	return _weaponLevel;
}

void PlayerPlane::setWeaponLevel(int val)
{
	val --;
	if (val < 0)
		val = 0;
	if (val >= (int)_listSupportedWeaponKey->count())
		val = (int)_listSupportedWeaponKey->count() - 1;
	_weaponLevel = val + 1;

	Weapon* wp = WeaponBank::sharedWeaponBank()->getWeapon((char*)dynamic_cast<CCString*>(_listSupportedWeaponKey->objectAtIndex(val))->getCString());
	PlaneShotStrategy* strategy = dynamic_cast<PlaneShotStrategy*>(_strategy);
	strategy->removeChild(strategy->getWeapon());
	strategy->addChild(wp);
	strategy->setWeapon(wp);

 	unschedule(SEL_SCHEDULE(&PlayerPlane::onShooting));
 	if (wp->getTimeDelay() != 0)
 		schedule(SEL_SCHEDULE(&PlayerPlane::onShooting));
}

int PlayerPlane::getMaxHealth()
{
	return _maxHealth;
}

void PlayerPlane::setMaxHealth(int var)
{
	_maxHealth = var;
	setHealth(var);
}

int PlayerPlane::getHealth()
{
	return _health;
}

void PlayerPlane::setHealth(int var)
{
	_health = var;
	if (_healthBar)
		_healthBar->setPercent((float)_health/_maxHealth * 100);
}

void PlayerPlane::shoot( Bullet* bullet )
{
	getMainLayer()->addPlayerBullet(bullet);
}

void PlayerPlane::onShot( Bullet* bullet )
{
	if (!_isProtected)
		setHealth(getHealth() - bullet->getDamage());
	Effect* ef = EffectFactory::sharedEffectFactory()->createEffect(EXPLOSIVE_2);
	ef->setPosition(ccp(bullet->boundingBox().getMidX(), bullet->boundingBox().getMidY()));
	getMainLayer()->getEffectManager()->addEffect(ef);
}

void PlayerPlane::startShoot( CCNode* sender )
{
	setWeaponLevel(9);
}
